/*
 *   Copyright [2008] [Anay Nayak]
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.googlecode.equalsnhashcode.finders;

import com.googlecode.equalsnhashcode.utils.NonStaticFieldConstraint;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiRecursiveElementVisitor;
import com.intellij.psi.PsiReferenceExpression;

import java.util.ArrayList;
import java.util.List;

public class PsiFieldElementVisitor extends PsiRecursiveElementVisitor {
    private List<PsiField> psiFields = new ArrayList<PsiField>();

    public void visitField(PsiField psiField) {
        if (!new NonStaticFieldConstraint().isSatisfiedBy(psiField))
            return;
        psiFields.add(psiField);
    }

    public List<PsiField> getPsiFields() {
        return psiFields;
    }

    public void visitReferenceExpression(PsiReferenceExpression psiReferenceExpression) {
        PsiElement element = resolveElement(psiReferenceExpression);
        if (belongsToCurrentClass(psiReferenceExpression) && isAField(element))
            element.accept(this);
        visitExpression(psiReferenceExpression);
    }

    private PsiElement resolveElement(PsiReferenceExpression psiReferenceExpression) {
        return psiReferenceExpression.resolve();
    }

    private boolean isAField(PsiElement element) {
        return element != null && element.isValid();
    }

    private boolean belongsToCurrentClass(PsiReferenceExpression psiReferenceExpression) {
        return psiReferenceExpression.getQualifierExpression() == null;
    }
}
